package com.mkyong.common.controller;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;
import org.jboss.logging.Logger;

public class BootstrapDataPopulator /*implements InitializingBean*/ {

	private static final Logger log = Logger.getLogger(BootstrapDataPopulator.class);
	
	private SessionFactory sessionFactory;
	//private transient final Log log = LogFactory.getLog(getClass());

	// Spring's transaction manager - needed to ensure data is inserted in a
	// transaction:
	// any failures, and we can roll back everything.
	//private PlatformTransactionManager transactionManager = null;

	// all other managers/dependencies here

	public BootstrapDataPopulator() {
	}

	//public void setTransactionManager(
	//		PlatformTransactionManager transactionManager) {
	//	this.transactionManager = transactionManager;
	//}

	// other dependency setter methods

	//@Override
	public void populateData() throws Exception {
		log.info("populateData entry");
		Student student = new Student();
		student.setName("some student");
		Address address = new Address();
		address.setFirstLine("Krakow");
		address.setSecondLine("Polska");
		student.setAddress(address);
		Grade g = new Grade();
		g.setValue(4);
		g.setStudent(student);
		Grade g2 = new Grade();
		g2.setStudent(student);
		g2.setValue(3);
		student.addGrade(g);
		student.addGrade(g2);
		
		Session session = sessionFactory.openSession();
		Transaction tx = session.beginTransaction();
		
		session.save(student);
		
		tx.commit();
		
		//Transaction tx2 = session.beginTransaction();
		
		//Criteria criteria = session.createCriteria(Student.class);
		//criteria.add(Restrictions.sqlRestriction("lower({alias}.address.firstLine) = ?", "Krakow", new StringType()));
		//log.info("RESULT" + ((Student) criteria.list().get(0)).getName());
		
		//tx2.commit();
		//		if (this.transactionManager == null) {
//			throw new IllegalStateException(
//					"transactionManager property must be set.");
//		}
		// assert other injected dependencies here

//		TransactionTemplate txnTemplate = new TransactionTemplate(
//				this.transactionManager);
//		txnTemplate.afterPropertiesSet();
//
//		txnTemplate.execute(new TransactionCallback() {
//			public Object doInTransaction(TransactionStatus status) {
//				try {
//					insertBoostrapData();
//				} catch (Exception e) {
//					// error - roll back. Runtime exception triggers rollback:
//					if (e instanceof RuntimeException) {
//						throw (RuntimeException) e;
//					} else {
//						throw new RuntimeException(e);
//					}
//				}
//				return null;
//			}
//		});
	}

	//private boolean guestUserExists() {
		//return userManager.findUserByUsername("guest") != null;
	//}

	protected void insertBoostrapData() throws Exception {
		// if the guest user account exists, take this as a sign that the
		// bootstrap data populator has
		// already been run, so just exit quietly:
//		if (guestUserExists()) {
//			if (log.isDebugEnabled()) {
//				log.debug("Bootstrap data insertion has already occurred. Returning quietly.");
//			}
//			return;
//		}
//
//		if (log.isInfoEnabled()) {
//			log.info("Inserting bootstrap data...");
//		}
//
//		// otherwise, populate bootstrap data:
//		log.debug("Creating guest user...");
//		User guestUser = someManager.create(new User("Guest",
//				"guest@domain.com"));
//
//		// insert all other objects and call any other helper methods here

	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}